import { create } from 'zustand';
import type { User } from '@/types';
import { userApi } from '@/api/user';
import { getUserRoutes } from '@/api/system';
import type { UserPermissionData } from '@/api/system';

interface UserState {
  user: User | null;
  isLoading: boolean;
  permissions: UserPermissionData | null;

  // Actions
  getUserInfo: () => Promise<void>;
  getUserPermissions: () => Promise<UserPermissionData>;
  refreshPermissions: () => Promise<void>;
  setUser: (user: User) => void;
  setPermissions: (permissions: UserPermissionData) => void;
  clearUser: () => void;
  clearPermissions: () => void;
  setLoading: (loading: boolean) => void;
}

export const useUserStore = create<UserState>((set, get) => ({
  // 从localStorage初始化用户信息
  user: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')!) : null,
  isLoading: false,
  // 从localStorage初始化权限信息
  permissions: localStorage.getItem('userPermissions') ? JSON.parse(localStorage.getItem('userPermissions')!) : null,

  getUserInfo: async () => {
    try {
      set({ isLoading: true });
      const user = await userApi.getUserInfo();

      // 保存用户信息到localStorage
      localStorage.setItem('userInfo', JSON.stringify(user));

      set({ user, isLoading: false });
    } catch (error) {
      set({ isLoading: false });
      throw error;
    }
  },

  getUserPermissions: async () => {
    const { permissions } = get();

    // 如果已经有缓存的权限数据，直接返回
    if (permissions) {
      return permissions;
    }

    // 否则从服务器获取
    return get().refreshPermissions();
  },

  refreshPermissions: async () => {
    try {
      set({ isLoading: true });
      const permissions = await getUserRoutes();

      // 动态修改菜单数据，为"系统管理"菜单添加 redirect 字段
      if (permissions && permissions.menus && Array.isArray(permissions.menus)) {
        const updatedMenus = permissions.menus.map(menu => {
          // 如果是系统管理菜单且没有 redirect 字段，则添加 redirect
          if (menu.name === '系统管理' && !menu.redirect) {
            return {
              ...menu,
              redirect: '/system/users'
            };
          }
          return menu;
        });

        // 更新权限数据
        const updatedPermissions = {
          ...permissions,
          menus: updatedMenus
        };

        // 保存权限信息到localStorage
        localStorage.setItem('userPermissions', JSON.stringify(updatedPermissions));

        set({ permissions: updatedPermissions, isLoading: false });
        return updatedPermissions;
      }

      // 保存权限信息到localStorage
      localStorage.setItem('userPermissions', JSON.stringify(permissions));

      set({ permissions, isLoading: false });
      return permissions;
    } catch (error) {
      set({ isLoading: false });

      // 对于401错误，清除权限缓存但不抛出错误
      if ('code' in (error as any) && (error as any).code === 401) {
        get().clearPermissions();
        // 返回一个空的权限对象而不是抛出错误
        return {
          menus: [],
          permissions: [],
          roles: []
        };
      }

      throw error;
    }
  },

  
  setUser: (user: User) => {
    // 保存用户信息到localStorage
    localStorage.setItem('userInfo', JSON.stringify(user));
    set({ user });
  },

  setPermissions: (permissions: UserPermissionData) => {
    // 保存权限信息到localStorage
    localStorage.setItem('userPermissions', JSON.stringify(permissions));
    set({ permissions });
  },

  clearUser: () => {
    localStorage.removeItem('userInfo');
    set({ user: null });
  },

  clearPermissions: () => {
    localStorage.removeItem('userPermissions');
    set({ permissions: null });
  },

  setLoading: (loading: boolean) => {
    set({ isLoading: loading });
  },
}));